package com.tfswx.jcyw.ruleenginedesigner.advice;

import com.tfswx.jcyw.ruleenginedesigner.bean.ApiResult;
import com.tfswx.jcyw.ruleenginedesigner.util.ExceptionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author Ricky
 * @date 2020-7-22 10:35
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionAdvice {

    @ResponseBody
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Exception.class)
    public ApiResult<Object> handlerMethodException(HttpServletRequest req, Exception e) {

        String errmsg = ExceptionUtil.getMessage(e);

        log.error("全局{}异常捕获：{}", e.getClass().getSimpleName(), errmsg, e);

        return ApiResult.fail(errmsg);
    }

    @ResponseBody
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ApiResult<Object> resolveMethodArgumentNotValidException(MethodArgumentNotValidException e) {

        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < allErrors.size(); i++) {
            ObjectError error = allErrors.get(i);
            sb.append(i + 1).append("：").append(error.getDefaultMessage()).append(";");
        }

        String errmsg = sb.toString();

        log.error("全局{}异常捕获：{}", e.getClass().getSimpleName(), errmsg, e);

        return ApiResult.fail(errmsg);
    }

    @ResponseBody
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(BindException.class)
    public ApiResult<Object> resolveBindException(BindException e) {

        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < allErrors.size(); i++) {
            ObjectError error = allErrors.get(i);
            sb.append(i + 1).append("：").append(error.getDefaultMessage()).append(";");
        }

        String errmsg = sb.toString();

        log.error("全局{}异常捕获：{}", e.getClass().getSimpleName(), errmsg, e);

        return ApiResult.fail(errmsg);
    }
}
